package com.service;
import com.dao.UserDao;
import com.entity.MyUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service("userService")
public class UserService implements UserDetailsService
{
    @Autowired
    private UserDao userDao;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        MyUser myUser = userDao.findUserByUsername(username);
        if (myUser == null)
        {
            throw new UsernameNotFoundException("查无此人！");
        }
        return myUser;
    }

    public boolean register(String username, String password ,String phoneNumber)
    {
        MyUser myUser = userDao.findUserByUsername(username);
        if (myUser == null)
        {
            String role;
            int userCount = userDao.getUserCount();
            if (userCount == 0) {
                role = "ADMIN";
            } else {
                role = "USER";
            }
            String password1 = passwordEncoder.encode(password);
            userDao.registerUser(username, password1, phoneNumber,role);
            return true;
        }
        return false;

    }

    public boolean modifyPwd(String username,String password){
        MyUser myUser = userDao.findUserByUsername(username);
        if (myUser != null){
            if (userDao.modifyPwd(passwordEncoder.encode(password),username)){
                return true;
            }
        }
        return false;
    }

}
